package com.wn.icloud.provider.uac.controller;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping(value = "/api/download")
public class AppDownLoadController {

    private static final Logger log =  LoggerFactory.getLogger(AppDownLoadController.class);
    @GetMapping("/app")
    public void appDownLoad(HttpServletResponse response,String name) throws Exception {
        if (StringUtils.isEmpty(name)){
            return;
        }
        // 下载本地文件
        String fileName = "企业码.apk".toString(); // 文件的默认保存名
        // 读到流中
        InputStream inStream = new FileInputStream("/opt/qiyema/" + name);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("multipart/form-data");
        response.addHeader("Content-Disposition", "attachment; filename=" +  new String(fileName.getBytes(), "ISO8859-1"));
        // 循环取出流中的数据
        byte[] b = new byte[1000];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
        } catch (IOException e) {
            log.error("下载apk失败",e);
        }finally {
            if (response.getOutputStream() != null){
                response.getOutputStream().close();
            }
            inStream.close();
        }
    }
    /**
     * 导出模板
     *
     * @param path
     * @param fileName
     * @param response
     */
    public static void exportTemplate(String path, String fileName, HttpServletResponse response) {
        try {
            response.setContentType("application/apk;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".apk");
            ServletOutputStream out = response.getOutputStream();
            byte[] byteFile = IOUtils.toByteArray(new ClassPathResource(path).getInputStream());
            out.write(byteFile);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException("模板获取失败！！");
        }
    }
}
